package com.cmp.generator.util;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.cmp.generator.model.DatabaseConfig;
import com.cmp.generator.model.GeneratorConfig;

import java.util.Collections;

/**
 * @author chen zhan mei
 * @date 2022 /11/24 8:12
 */
public class MpGenerator {

    private final GeneratorConfig generatorConfig;
    private final DatabaseConfig databaseConfig;

    public MpGenerator(GeneratorConfig generatorConfig, DatabaseConfig databaseConfig) {
        this.generatorConfig = generatorConfig;
        this.databaseConfig = databaseConfig;
    }

    public void generate() {
        DataSourceConfig.Builder b = new DataSourceConfig.Builder(
                DbUtil.getConnectionUrlWithSchema(databaseConfig),
                databaseConfig.getUsername(),
                databaseConfig.getPassword()
        );
        FastAutoGenerator.create(b)
                .globalConfig(builder -> {
                    builder.author(generatorConfig.getAuthor()) // 设置作者
                            .outputDir(generatorConfig.getProjectFolder()); // 指定输出目录
                    if (generatorConfig.isSwagger()) {
                        builder.enableSwagger();
                    }
                    if (!generatorConfig.isOpen()) {
                        builder.disableOpenDir();
                    }
                    if (generatorConfig.isFileOverride()) {
                        builder.fileOverride();
                    }
                    if (generatorConfig.isKotlin()) {
                        builder.enableKotlin();
                    }
                })
                .packageConfig(builder -> {
                    builder.parent(generatorConfig.getModelPackage()) // 设置父包名
                            .pathInfo(Collections.singletonMap(OutputFile.xml, generatorConfig.getProjectFolder())); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude(generatorConfig.getTableName()) // 设置需要生成的表名
                            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine())
                // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                .execute();


    }
}
